﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Common.Library;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using System.Collections.ObjectModel;
using OnlineVideos.UI;
using System.IO;
using ImageTools.IO.Gif;
using ImageTools.IO.Png;
using System.IO.IsolatedStorage;
using Microsoft.Phone;
using ImageTools.IO.Jpeg;
using Common.Utilities;

namespace OnlineMovies.Views
{
    public partial class OnlineImages : PhoneApplicationPage
    {
        ObservableCollection<ImageSource> source = new ObservableCollection<ImageSource>();
        int count1 = 0;
        int count = 0;
        public OnlineImages()
        {
            InitializeComponent();
            Loaded += OnlineImages_Loaded;
        }
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            try
            {
                FlurryWP8SDK.Api.EndTimedEvent("OnlineImages Page");
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in OnNavigatedFrom Method In OnlineImages.cs file.", ex);
            }
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            try
            {
                FlurryWP8SDK.Api.LogPageView();
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in OnNavigatedTo Method In OnlineImages.cs file.", ex);
            }
        }
        void OnlineImages_Loaded(object sender, RoutedEventArgs e)
        {
            if(ResourceHelper.AppName!=Apps.Indian_Cinema_Pro.ToString() && ResourceHelper.AppName!=Apps.Kids_TV_Pro.ToString() && ResourceHelper.AppName!=Apps.Story_Time_Pro.ToString())
            LoadAds();
            try
            {
                FlurryWP8SDK.Api.LogEvent("OnlineImages Page", true);
                if (Constants.OnlineImageUrls.Count > 0)
                {
                    _PerformanceProgressBar.IsIndeterminate = true;
                    lbxImages.ItemsSource = source;
                    foreach (string url in Constants.OnlineImageUrls.Where(i => i != null))
                    {
                        if (url.EndsWith(".gif") && (ResourceHelper.AppName == Apps.Online_Education.ToString() || ResourceHelper.AppName == Apps.DrivingTest.ToString()))
                        {
                            WebClient client = new WebClient();
                            if (url.StartsWith("http"))
                                client.OpenReadAsync(new Uri(url));
                            else
                                client.OpenReadAsync(new Uri("http://" + url));
                            client.OpenReadCompleted += client_OpenReadCompleted;
                        }
                        else
                        {
                            BitmapImage bitmap = new BitmapImage();
                            bitmap.CreateOptions = BitmapCreateOptions.None;
                            bitmap.UriSource = new Uri(url, UriKind.RelativeOrAbsolute);
                            bitmap.ImageOpened += bitmap_ImageOpened;
                            bitmap.ImageFailed += bitmap_ImageFailed;
                        }

                    }

                    notavailablemes.Visibility = Visibility.Collapsed;
                }
                else
                {
                    notavailablemes.Visibility = Visibility.Visible;
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in LoadAds Method In SongDetails file", ex);
                string excepmess = "Exception in LoadAds Method In SongDetails file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }
        }
           
        #region "Common Methods"

        private void LoadAds()
        {
            try
            {
                PageHelper.LoadAdControl(LayoutRoot, adstackpl, 1);
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in LoadAds Method In SongDetails file", ex);
                string excepmess = "Exception in LoadAds Method In SongDetails file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }

        }

        #endregion

        void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            try
            {
            MemoryStream str = new MemoryStream();
            GifDecoder gd = new GifDecoder();
            ImageTools.ExtendedImage img = new ImageTools.ExtendedImage();
            gd.Decode(img, e.Result);              //stream means image stream
            JpegEncoder png = new JpegEncoder();
            png.Encode(img, str);
         
            BitmapImage bitmap = new BitmapImage();
            bitmap.CreateOptions = BitmapCreateOptions.None;
            bitmap.SetSource(str);
            source.Add(bitmap);
            if (++count == Constants.OnlineImageUrls.Count)
            {
                _PerformanceProgressBar.IsIndeterminate = false;
            }
        }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in client_OpenReadCompleted Method In OnlineImages.cs file.", ex);
            }
        }

        void bitmap_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {
            try
            {
           
            if (++count == Constants.OnlineImageUrls.Count)
            {
                _PerformanceProgressBar.IsIndeterminate = false;
            }
            }
            catch (Exception ex)
            {
           
                 Exceptions.SaveOrSendExceptions("Exception in bitmap_ImageFailed Method In OnlineImages.cs file.", ex);
        }

        }

        void bitmap_ImageOpened(object sender, RoutedEventArgs e)
        {
            try
            {
            source.Add((sender as BitmapImage) as ImageSource);

            if (++count == Constants.OnlineImageUrls.Count)
            {
                _PerformanceProgressBar.IsIndeterminate = false;
            }
        }
            catch (Exception ex)
            {

             Exceptions.SaveOrSendExceptions("Exception in bitmap_ImageOpened Method In OnlineImages.cs file.", ex);
            }
        }

        //private void CheckBox_Checked(object sender, RoutedEventArgs e)
        //{
        //    Constants.UserImage =new BitmapImage();
        //    Constants.UserImage.UriSource=new Uri(((sender as CheckBox).Tag as BitmapImage).UriSource.ToString(),UriKind.RelativeOrAbsolute);
        //    NavigationService.GoBack();
        //}

        private void imgTitle_MouseEnter(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            NavigationService.Navigate(NavigationHelper.MainPanoramaPage);
        }

      

        private void lbxImages_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            try
            {
            Constants.UserImage1 = new BitmapImage();
                if (string.IsNullOrEmpty(((BitmapImage)(sender as ListBox).SelectedItem).UriSource.ToString()))
                    Constants.UserImage1 = ((BitmapImage)(sender as ListBox).SelectedItem);
            else
            Constants.UserImage1.UriSource = new Uri(((BitmapImage)(sender as ListBox).SelectedItem).UriSource.ToString(), UriKind.RelativeOrAbsolute);
            NavigationService.GoBack();
        }
            catch (Exception ex)
            {
                
               Exceptions.SaveOrSendExceptions("Exception in lbxImages_SelectionChanged_1 Method In OnlineImages.cs file.", ex);
            }
        }

       

       
    }
}